package withouther.system.core.security.handle;

import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import withouther.system.core.result.WhResult;
import withouther.system.core.util.SecurityUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname WhAccessDeineHandler
 * @Description 用来解决匿名用户访问无权限资源时的异常
 * @Author tzq
 * @Date 2020/03/19 3:35 下午
 * @Version 1.0
 */
@Component
@Slf4j
public class WhAccessDeineHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String message = "请求访问: " + request.getRequestURI() + " 接口， 没有访问权限";
        SecurityUtil.write(response, WhResult.fail(HttpStatus.HTTP_UNAUTHORIZED, message));
        log.error(message);
    }
}
